package com.hwpt.hwaccount.feature.security;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hwpt.hwaccount.R;
import com.hwpt.hwaccount.core.data.local.entity.UserEntity;
import com.hwpt.hwaccount.feature.auth.ui.RepwdActivity;

public class SecurityActivity extends AppCompatActivity implements SecurityContract.View {

    private SecurityContract.Presenter presenter;
    private UserEntity currentUser;

    private View changePasswordLayout;
    private View emergencyContactLayout;
    private View privacyPolicyLayout;
    private View phoneBindLayout;
    private View emailBindLayout;

    private TextView emergencyContactText;
    private TextView phoneText;
    private TextView emailText;
    private TextView hanwangIdText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_security_settings);

        initView();

        SecurityContract.Model model = new SecurityModel(this);
        presenter = new SecurityPresenter(model);
        presenter.attachView(this);

        presenter.loadSecurityInfo();
    }

    private void initView() {
        changePasswordLayout = findViewById(R.id.change_password_layout);
        emergencyContactLayout = findViewById(R.id.emergency_contact_layout);
        privacyPolicyLayout = findViewById(R.id.privacy_policy_layout);

        emergencyContactText = findViewById(R.id.emergency_contact_text);

        phoneBindLayout = findViewById(R.id.phone_bind_layout);
        emailBindLayout = findViewById(R.id.email_bind_layout);

        phoneText = findViewById(R.id.phone_text);
        emailText = findViewById(R.id.email_text);
        hanwangIdText = findViewById(R.id.hanwang_id_text);

        changePasswordLayout.setOnClickListener(v -> showChangePasswordDialog());
        emergencyContactLayout.setOnClickListener(v -> showEmergencyContactDialog());
        privacyPolicyLayout.setOnClickListener(v -> showPrivacyPolicy());
        phoneBindLayout.setOnClickListener(v -> showPhoneBindDialog());
        emailBindLayout.setOnClickListener(v -> showEmailBindDialog());
    }

    @Override
    public void showSecurityInfo(UserEntity user) {
        currentUser = user;

        hanwangIdText.setText(user.getHanWangId() != null ? user.getHanWangId() : "未设置");

        boolean hasEmergencyContact = user.getContactName() != null && !user.getContactName().isEmpty()
                && user.getContactMobile() != null && !user.getContactMobile().isEmpty();
        String emergencyContactStatus = hasEmergencyContact ? "已设置" : "未设置";
        emergencyContactText.setText(emergencyContactStatus);

        if (user.getPhone() != null && !user.getPhone().isEmpty()) {
            phoneText.setText(user.getPhone());
        } else {
            phoneText.setText("未绑定");
        }

        if (user.getEmail() != null && !user.getEmail().isEmpty()) {
            emailText.setText(user.getEmail());
        } else {
            emailText.setText("未绑定");
        }
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showSuccess(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void showChangePasswordDialog() {
        Intent intent = new Intent(this, RepwdActivity.class);
        startActivity(intent);
    }

    private void showEmergencyContactDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("紧急联系人");

        boolean hasEmergencyContact = currentUser != null
                && currentUser.getContactName() != null && !currentUser.getContactName().isEmpty()
                && currentUser.getContactMobile() != null && !currentUser.getContactMobile().isEmpty();

        if (!hasEmergencyContact) {
            showEmergencyContactSetupDialog(builder);
        } else {
            showEmergencyContactManageDialog(builder);
        }
    }

    private void showEmergencyContactSetupDialog(AlertDialog.Builder builder) {
        View view = getLayoutInflater().inflate(R.layout.dialog_emergency_contact, null);

        EditText contactNameEditText = view.findViewById(R.id.contact_name);
        EditText contactPhoneEditText = view.findViewById(R.id.contact_phone);
        EditText relationshipEditText = view.findViewById(R.id.relationship);

        if (currentUser != null) {
            if (currentUser.getContactName() != null) {
                contactNameEditText.setText(currentUser.getContactName());
            }
            if (currentUser.getContactMobile() != null) {
                contactPhoneEditText.setText(currentUser.getContactMobile());
            }
            if (currentUser.getRelationship() != null) {
                relationshipEditText.setText(currentUser.getRelationship());
            }
        }

        builder.setView(view);
        builder.setPositiveButton("设置", (dialog, which) -> {
            String name = contactNameEditText.getText().toString().trim();
            String phone = contactPhoneEditText.getText().toString().trim();
            String relationship = relationshipEditText.getText().toString().trim();

            if (name.isEmpty() || phone.isEmpty() || relationship.isEmpty()) {
                showError("请填写完整信息");
                return;
            }

            presenter.setupEmergencyContact(name, phone, relationship);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showEmergencyContactManageDialog(AlertDialog.Builder builder) {
        View view = getLayoutInflater().inflate(R.layout.dialog_emergency_contact_manage, null);

        TextView currentContactTextView = view.findViewById(R.id.current_contact);
        String contactInfo = "姓名: " + currentUser.getContactName() +
                "\n电话: " + currentUser.getContactMobile() +
                "\n关系: " + currentUser.getRelationship();
        currentContactTextView.setText(contactInfo);

        builder.setView(view);
        builder.setPositiveButton("修改", (dialog, which) -> {
            showEmergencyContactSetupDialog(new AlertDialog.Builder(this));
        });
        builder.setNeutralButton("删除", (dialog, which) -> {
            presenter.setupEmergencyContact("", "", "");
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showPrivacyPolicy() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("隐私政策");
        builder.setMessage("这里是隐私政策内容...\n\n我们承诺保护您的隐私安全。");
        builder.setPositiveButton("确定", null);
        builder.show();
    }

    private void showPhoneBindDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        boolean isPhoneBound = currentUser != null && currentUser.getPhone() != null && !currentUser.getPhone().isEmpty();

        if (!isPhoneBound) {
            builder.setTitle("绑定手机号");

            View view = getLayoutInflater().inflate(R.layout.dialog_bind_phone, null);
            EditText phoneEditText = view.findViewById(R.id.phone_number);
            EditText verifyCodeEditText = view.findViewById(R.id.verify_code);
            Button getCodeButton = view.findViewById(R.id.get_verify_code);

            getCodeButton.setOnClickListener(v -> {
                String phone = phoneEditText.getText().toString().trim();
                if (phone.isEmpty()) {
                    showError("请输入手机号");
                    return;
                }
                presenter.sendPhoneVerifyCode(phone);
            });

            builder.setView(view);
            builder.setPositiveButton("绑定", (dialog, which) -> {
                String phone = phoneEditText.getText().toString().trim();
                String code = verifyCodeEditText.getText().toString().trim();

                if (phone.isEmpty() || code.isEmpty()) {
                    showError("请填写完整信息");
                    return;
                }

                presenter.bindPhone(phone, code);
            });
        } else {
            builder.setTitle("手机号管理");

            View view = getLayoutInflater().inflate(R.layout.dialog_phone_manage, null);
            TextView phoneTextView = view.findViewById(R.id.current_phone);
            phoneTextView.setText("当前绑定的手机号: " + currentUser.getPhone());

            builder.setView(view);
            builder.setPositiveButton("更换手机号", (dialog, which) -> {
                presenter.unbindPhone();
            });
            builder.setNeutralButton("解绑", (dialog, which) -> {
                presenter.unbindPhone();
            });
        }

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showEmailBindDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        boolean isEmailBound = currentUser != null && currentUser.getEmail() != null && !currentUser.getEmail().isEmpty();

        if (!isEmailBound) {
            builder.setTitle("绑定邮箱");

            View view = getLayoutInflater().inflate(R.layout.dialog_bind_email, null);
            EditText emailEditText = view.findViewById(R.id.email_address);
            EditText verifyCodeEditText = view.findViewById(R.id.verify_code);
            Button getCodeButton = view.findViewById(R.id.get_verify_code);

            getCodeButton.setOnClickListener(v -> {
                String email = emailEditText.getText().toString().trim();
                if (email.isEmpty()) {
                    showError("请输入邮箱地址");
                    return;
                }
                presenter.sendEmailVerifyCode(email);
            });

            builder.setView(view);
            builder.setPositiveButton("绑定", (dialog, which) -> {
                String email = emailEditText.getText().toString().trim();
                String code = verifyCodeEditText.getText().toString().trim();

                if (email.isEmpty() || code.isEmpty()) {
                    showError("请填写完整信息");
                    return;
                }

                presenter.bindEmail(email, code);
            });
        } else {
            builder.setTitle("邮箱管理");

            View view = getLayoutInflater().inflate(R.layout.dialog_email_manage, null);
            TextView emailTextView = view.findViewById(R.id.current_email);
            emailTextView.setText("当前绑定的邮箱: " + currentUser.getEmail());

            builder.setView(view);
            builder.setPositiveButton("更换邮箱", (dialog, which) -> {
                presenter.bindEmail("", "");
            });
        }

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter.onDestroy();
        }
        super.onDestroy();
    }
}